package com.sto.stoapp.log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Vector;

import android.annotation.SuppressLint;
import android.os.Environment;

import com.sto.stoapp.file.LogFileListItem;
import com.sto.stoapp.util.Helper;

/**
 * 异常日志记录
 * 
 * @author mgf
 * 
 */
@SuppressLint("SimpleDateFormat")
public class ExceptionLog {
	
	/**
	 * 异常文件名头
	 */
	private static final String LOG_FILE_NAME = "error_log_";
	
	/**
	 * 申通
	 */
	public static final String LOG_STO = "sto";
	
	/**
	 * log
	 */
	private static final String LOG = "log";
	
//	public static final String LOG_FILE_NAME = "sto_error_log.txt";
	
	private static File root;
	
	public static final String DATE_FORMAT = "yyyyMMdd";
	
	public static final String MONTH_FORMAT = "yyyyMM";
	
	/**
	 * 文件后缀名
	 */
	private static final String FILE_SUFFIX = ".txt";
	
	private static ExceptionLog log;
	
	public static ExceptionLog getInstance(){
		if(log == null){
			log = new ExceptionLog();	
		}
		
		return log;
	}
	
	private ExceptionLog() {
		// TODO Auto-generated constructor stub3
		init();
		
	}
	
	/**
	 * 初始化日志
	 * @author wxf
	 *
	 */
	public static void init(){
		root = Environment.getExternalStorageDirectory();
		File sto = new File(root.getAbsolutePath() + File.separator
				+ LOG_STO);
		if (!sto.exists()) {
			sto.mkdir();
		}
		File log = new File(root.getAbsolutePath() + File.separator
				+ LOG_STO + File.separator + LOG);
		if (!log.exists()) {
			log.mkdir();
		}
		
	}
	
	/**
	 * 得到异常日志保存路径
	 * 
	 * @return
	 */
	public String getPath() {
		return root.getAbsolutePath() + File.separator + LOG_STO
				+ File.separator + LOG;
	}

	/**
	 * 写文件
	 * 
	 * @param title
	 *            标题
	 * @param content
	 *            内容
	 */
	public static void writeLog(String title, String content) {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			try {
				/*File root = Environment.getExternalStorageDirectory();
				File log = new File(root.getAbsolutePath() + File.separator
						+ LOG_FILE_NAME);
				if (!log.exists()) {
					log.createNewFile();
				}*/
				File root = Environment.getExternalStorageDirectory();

				String monthFile = new SimpleDateFormat(MONTH_FORMAT)
				.format(new Date());
				
				File monthLog = new File(root.getAbsolutePath() + File.separator
						+ LOG_STO + File.separator + LOG + File.separator + monthFile);
				if (!monthLog.exists()) {
					monthLog.mkdir();
				}
				
				String dateFile = new SimpleDateFormat(DATE_FORMAT)
						.format(new Date());
				File txt = new File(root.getAbsolutePath() + File.separator
						+ LOG_STO + File.separator + LOG + File.separator + monthFile + File.separator
						+ LOG_FILE_NAME + dateFile + FILE_SUFFIX);
				if (!txt.exists()) {
					txt.createNewFile();
				}
				
				SimpleDateFormat sDateFormat = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				String date = sDateFormat.format(new java.util.Date());
				FileOutputStream osw = new FileOutputStream(txt, true);
				osw.write(date.getBytes());
				osw.write("\r\n".getBytes());
				osw.write(title.getBytes());
				osw.write("\r\n".getBytes());
				if (content != null) {
					osw.write(content.getBytes());
					osw.write("\r\n".getBytes());
					osw.write("\r\n".getBytes());
				}
				osw.close();
			} catch (Exception e) {
				e.getStackTrace();
			}
		}
	}

	/**
	 * 写文件
	 * 
	 * @param title
	 *            标题
	 */
	public static void writeLog(String title) {
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			try {
				/*File root = Environment.getExternalStorageDirectory();
				File log = new File(root.getAbsolutePath() + File.separator
						+ LOG_FILE_NAME);
				if (!log.exists()) {
					log.createNewFile();
				}*/
				
				/*File sto = new File(root.getAbsolutePath() + File.separator
						+ LOG_STO);
				if (!sto.exists()) {
					sto.mkdir();
				}
				File log = new File(root.getAbsolutePath() + File.separator
						+ LOG_STO + File.separator + LOG);
				if (!log.exists()) {
					log.mkdir();
				}*/
				
				String monthFile = new SimpleDateFormat(MONTH_FORMAT)
				.format(new Date());
				if(root == null){
					init();
				}
				File monthLog = new File(root.getAbsolutePath() + File.separator
						+ LOG_STO + File.separator + LOG + File.separator + monthFile);
				if (!monthLog.exists()) {
					monthLog.mkdir();
				}
				
				String dateFile = new SimpleDateFormat(DATE_FORMAT)
						.format(new Date());
				File txt = new File(root.getAbsolutePath() + File.separator
						+ LOG_STO + File.separator + LOG + File.separator + monthFile + File.separator
						+ LOG_FILE_NAME + dateFile + FILE_SUFFIX);
				if (!txt.exists()) {
					txt.createNewFile();
				}
				
				SimpleDateFormat sDateFormat = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				String date = sDateFormat.format(new java.util.Date());
				FileOutputStream osw = new FileOutputStream(txt, true);
				osw.write(date.getBytes());
				osw.write("\r\n".getBytes());
				osw.write(title.getBytes());
				osw.write("\r\n".getBytes());
				osw.close();
			} catch (Exception e) {
				e.getStackTrace();
				System.out.println(" === " + e.getMessage());
			}
		}
	}
	
	/**
	 * 根据读取异常日志
	 * 
	 * @param dateFile
	 *            日期格式：yyyyMMdd
	 * @return 异常日志内容
	 */
	public String readLog(String dateFile) {
		StringBuffer fileContent = new StringBuffer();
		try {
			File txt = new File(root.getAbsolutePath() + File.separator
					+ LOG_STO + File.separator + LOG + File.separator
					+ LOG_FILE_NAME + dateFile + FILE_SUFFIX);
			if (txt.isFile() && txt.exists()) {
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(txt), "utf-8");
				BufferedReader reader = new BufferedReader(read);
				String line;
				while ((line = reader.readLine()) != null) {
					fileContent.append(line);
					fileContent.append("\r\n");
				}
				read.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileContent.toString();
	}

	/**
	 * 根据异常日志文件读取异常日志内容
	 * 
	 * @param txt
	 * @return
	 */
	public String readLog(File txt) {
		StringBuffer fileContent = new StringBuffer();
		try {
			// File txt = new File(root.getAbsolutePath() + File.separator
			// + customType + File.separator + LOG + File.separator
			// + LOG_FILE_NAME + dateFile + FILE_SUFFIX);
			if (txt.isFile() && txt.exists()) {
				InputStreamReader read = new InputStreamReader(
						new FileInputStream(txt), "utf-8");
				BufferedReader reader = new BufferedReader(read);
				String line;
				while ((line = reader.readLine()) != null) {
					fileContent.append(line);
					fileContent.append("\r\n");
				}
				read.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return fileContent.toString();
	}

	/**
	 * 读取所有异常文件夹
	 * 
	 * @return
	 */
	public Vector<LogFileListItem> getAllExceptionFile() {
		Vector<LogFileListItem> fileList = new Vector<LogFileListItem>();
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			File aDirectory = new File(getPath());
			if (aDirectory.exists()) {
				for (File f : aDirectory.listFiles()) {
					if (f.isDirectory()) {
						for(File flist : f.listFiles()){
							
							if (checkExt(flist.getName().toLowerCase())) {
								LogFileListItem item = new LogFileListItem();
								item.name = flist.getName();
								item.fileName = flist.getPath();
								item.type = LogFileListItem.TXT_FILE;
								fileList.add(item);
							}
							/*LogFileListItem item = new LogFileListItem();
							item.name = f.getName();
							item.type = LogFileListItem.FOLDER;
							fileList.add(item);*/
						}
					} else {
						if (checkExt(f.getName().toLowerCase())) {
							LogFileListItem item = new LogFileListItem();
							item.name = f.getName();
							item.fileName = f.getPath();
							item.type = LogFileListItem.TXT_FILE;
							fileList.add(item);
						}
					}
				}
			}
		}
		return fileList;
	}

	private boolean checkExt(String itemName) {
		if (itemName.endsWith(LogFileListItem.mFileExt))
			return true;
		return false;
	}
	
	/**
	 * 删除三个月之前的日志
	 * @author wxf
	 *
	 */
	public void delLog(){
		Calendar calendar = Calendar.getInstance();
		// 得到前1个月
		calendar.add(Calendar.MONTH, -1);
		String monthNow = new SimpleDateFormat(MONTH_FORMAT)
		.format(calendar.getTime());
//		System.out.println("init()" + monthNow);
		if (Environment.MEDIA_MOUNTED.equals(Environment
				.getExternalStorageState())) {
			File aDirectory = new File(getPath());
			if (aDirectory.exists()) {
				for (File f : aDirectory.listFiles()) {
					if (f.isDirectory()) {
						if(Helper.isNumeric(f.getName())){
							if(Integer.parseInt(f.getName()) < Integer.parseInt(monthNow)){
								// 要删除的目录
								File[] childFiles = f.listFiles();
								if (childFiles == null || childFiles.length == 0) {
									f.delete();
									
									return;
								}
								for (File file : childFiles) {
									file.delete();
								}
								f.delete();
							}
						}
					}
				}
			}
		}
	}
	
}
